package com.yonyou.crm.cum.customer.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;

import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yonyou.crm.base.doc.service.BaseDocDetailBizServiceImpl;
import com.yonyou.crm.base.industry.service.IndustryBizServiceImpl;
import com.yonyou.crm.bpub.refervalue.entity.ReferDataVO;
import com.yonyou.crm.common.biz.service.BaseBizServiceImpl;
import com.yonyou.crm.common.enumeration.service.EnumBizServiceImpl;
import com.yonyou.crm.common.exception.CrmBusinessException;
import com.yonyou.crm.common.field.handler.FieldRelationHandler;
import com.yonyou.crm.common.field.relation.EnumFieldRelation;
import com.yonyou.crm.common.field.relation.FieldRelation;
import com.yonyou.crm.common.field.relation.RefFieldRelation;
import com.yonyou.crm.common.login.context.LoginContextConstant;
import com.yonyou.crm.common.model.util.IConverter;
import com.yonyou.crm.common.model.util.ModelUtil;
import com.yonyou.crm.common.page.entity.Page;
import com.yonyou.crm.common.search.entity.AppSearchPlanEnum;
import com.yonyou.crm.cum.contact.entity.ContactDO;
import com.yonyou.crm.cum.contact.service.ContactBizServiceImpl;
import com.yonyou.crm.cum.cumprmt.service.CumprmtBizServiceImpl;
import com.yonyou.crm.cum.customer.dynamic.DymCumDisable;
import com.yonyou.crm.cum.customer.dynamic.DymCumEnable;
import com.yonyou.crm.cum.customer.dynamic.DymCumIdentify;
import com.yonyou.crm.cum.customer.dynamic.DymCumIdentifyCancel;
import com.yonyou.crm.cum.customer.dynamic.DymCumLocationSave;
import com.yonyou.crm.cum.customer.dynamic.DymCumLocationUpdate;
import com.yonyou.crm.cum.customer.dynamic.DymCumStaffAdd;
import com.yonyou.crm.cum.customer.dynamic.DymCumStaffUpdate;
import com.yonyou.crm.cum.customer.dynamic.DymCustomerCreate;
import com.yonyou.crm.cum.customer.dynamic.DymCustomerUpdate;
import com.yonyou.crm.cum.customer.dynamic.DymGCumIdentify;
import com.yonyou.crm.cum.customer.dynamic.DymGCumIdentifyCancel;
import com.yonyou.crm.cum.customer.entity.CustomerDO;
import com.yonyou.crm.cum.customer.entity.CustomerRelusersVO;
import com.yonyou.crm.cum.customer.entity.CustomerSalesDO;
import com.yonyou.crm.cum.customer.entity.CustomerSalesVO;
import com.yonyou.crm.cum.customer.entity.CustomerVO;
import com.yonyou.crm.cum.customer.entity.CustomerViewDO;
import com.yonyou.crm.sprc.opportunity.entity.OpportunityVO;
import com.yonyou.crm.sprc.opportunity.service.OpportunityBizServiceImpl;
import com.yonyou.crm.sys.dataright.entity.RightActionEnum;
import com.yonyou.crm.sys.dataright.entity.RightObjectEnum;
import com.yonyou.crm.sys.dataright.service.RightServiceImpl;
import com.yonyou.crm.sys.dynamic.builder.Field;
import com.yonyou.crm.sys.dynamic.builder.Link;
import com.yonyou.crm.sys.dynamic.entity.DynamicVO;
import com.yonyou.crm.sys.dynamic.filter.BusiFilter;
import com.yonyou.crm.sys.dynamic.filter.DateTimeFilter;
import com.yonyou.crm.sys.dynamic.filter.MyFilter;
import com.yonyou.crm.sys.dynamic.impl.DynamicServiceImpl;
import com.yonyou.crm.sys.modules.entity.MtObjTypeEnum;
import com.yonyou.crm.sys.modules.service.BiztypeBizServiceImpl;
import com.yonyou.crm.sys.org.service.SysOrgBizServiceImpl;
import com.yonyou.crm.sys.queryplan.service.QueryPlanBizService;
import com.yonyou.crm.sys.region.service.RegionsBizServiceImpl;
import com.yonyou.crm.sys.role.entity.FuncresourceVO;
import com.yonyou.crm.sys.role.service.FunctionBizServiceImpl;
import com.yonyou.crm.sys.role.service.RoleBizServiceImpl;
import com.yonyou.crm.sys.user.entity.UserVO;
import com.yonyou.crm.sys.user.service.UserBizServiceImpl;
import com.yonyou.iuap.context.InvocationInfoProxy;

@Service
public class CustomerBizServiceImpl extends BaseBizServiceImpl<CustomerDO> {

    @Autowired
    private CustomerViewBizServiceImpl viewService;
    @Autowired
    private EnumBizServiceImpl enumService;
    @Autowired
    private RegionsBizServiceImpl regionService;
    @Autowired
    private BaseDocDetailBizServiceImpl baseDocDetailBizService;
    @Autowired
    private IndustryBizServiceImpl IndustryBizService;
    @Autowired
    private CustomerSalesBizServiceImpl saleService;
    @Autowired
    private SysOrgBizServiceImpl orgService;
    @Autowired
    private UserBizServiceImpl userService;
    @Autowired
    private RoleBizServiceImpl roleService;
    @Autowired
    private RightServiceImpl rightService;
    @Autowired
    private QueryPlanBizService queryService;
    @Autowired
    private OpportunityBizServiceImpl oppService;
    @Autowired
    private CumprmtBizServiceImpl cumprmService;
    @Autowired
    private CustomerRelusersBizServiceImpl cusreluserService;
    @Autowired
    private ContactBizServiceImpl contactService;
    @Autowired
	private DynamicServiceImpl dynamicService;
    @Autowired
    private FunctionBizServiceImpl funcService;
    @Autowired
    private BiztypeBizServiceImpl biztypeService;
    
    public CustomerVO getDetail(Long id) {
        //判断是否有数据权限
        Long actionId = (long) RightActionEnum.VIEW.getValue();
        String crmMessage = hasRight(actionId, id);
        if (crmMessage != null) {
            throw new CrmBusinessException(crmMessage);
        }

        String orgIdStr = (String) InvocationInfoProxy.getParameter("orgid");//所属公司
        String tenantIdStr = (String) InvocationInfoProxy.getTenantid();
        Long orgId = Long.parseLong(orgIdStr);
        Long tenantId = Long.parseLong(tenantIdStr);

        CustomerDO custdo = super.getVOById(CustomerDO.class, id);
        CustomerVO vo = ModelUtil.copyModel(custdo, CustomerVO.class);

        Map<String, Object> param = new HashMap<String, Object>();
        param.put("tenantId", tenantId);
        param.put("cumId", id);
        // 根据权限判断是否能查看多个销售公司的销售信息，当前只支持单个。
        param.put("orgId", orgId);
        List<CustomerSalesVO> saleVOs = saleService.selectByCustomer(param);

        if (saleVOs.size() > 0) {
            vo.setSalesVOs(saleVOs);
        }
        transCustomer(Arrays.asList(vo));
        return vo;
    }

    public CustomerVO viewDetail(Long id) {
        CustomerVO vo = getDetail(id);
        CustomerViewDO viewDO = new CustomerViewDO();
        viewDO.setCumId(id);
        viewService.saveVO(viewDO);
        //transCustomer(Arrays.asList(vo));
        return vo;
    }

    public Page<CustomerVO> getList(Page<CustomerVO> page, Map<String, Object> paramMap) {
        //PC端使用
        if (paramMap.containsKey("province_city_district")) {
            String pcdStr = (String) paramMap.get("province_city_district");
            String[] pcd = pcdStr.split("_");
            if (pcd.length != 0 && pcd.length != 3) {
                throw new CrmBusinessException("查询参数格式错误");
            }
            try {
                paramMap.put("province", Integer.parseInt(pcd[0]));
                paramMap.put("city", Integer.parseInt(pcd[1]));
                paramMap.put("district", Integer.parseInt(pcd[2]));
            } catch (Exception e) {
                throw new CrmBusinessException("查询参数格式错误");
            }
            paramMap.remove("province_city_district");
        }

        if (paramMap.containsKey("option")) {
            // 查询方案，从库中查询？
            int searchPlan = (Integer) paramMap.get("option");
            paramMap.remove("option");
            if (searchPlan == AppSearchPlanEnum.ALL.getValue()) {// 当前全部客户只有我负责的
                return getMyOwnerList(page, paramMap);
            } else if (searchPlan == AppSearchPlanEnum.OWNER.getValue()) {// 我负责的
                return getMyOwnerList(page, paramMap);
            } else if (searchPlan == AppSearchPlanEnum.REL.getValue()) {//我参与的
                return getMyRelList(page, paramMap);
            } else if (searchPlan == AppSearchPlanEnum.FOLLOW.getValue()) {//我关注的
                return getMyFollowList(page, paramMap);
            } else if (searchPlan == AppSearchPlanEnum.VIEW.getValue()) {//最近查看的
                return getMyViewList(page, paramMap);
            } else if (searchPlan == AppSearchPlanEnum.WEEKFOLLOWUP.getValue()) {//一周未跟进
                //TODO一周未跟进查询
                return getMyOwnerList(page, paramMap);
            } else if (searchPlan == AppSearchPlanEnum.CREATE.getValue()) {//最近创建的
                return getMyOwnerList(page, paramMap);
            } else if (searchPlan == AppSearchPlanEnum.ASSIGNED.getValue()) {//已分配
                return getMyOwnerList(page, paramMap);
            } else if (searchPlan == AppSearchPlanEnum.UNASSIGNED.getValue()) {//未分配
                return getMyOwnerList(page, paramMap);
            }
        }

        //PC端根据查询方案查询客户
        paramMap = queryService.handleSearchPlan(paramMap);

        return getMyOwnerList(page, paramMap);
    }

    public Page<CustomerVO> getMyOwnerList(Page<CustomerVO> page, Map<String, Object> paramMap) {

        String userIdStr = (String) InvocationInfoProxy.getParameter("id");// 用户id
        String orgIdStr = (String) InvocationInfoProxy.getParameter("orgid");// 所属公司
        String tenantIdStr = (String) InvocationInfoProxy.getTenantid();
        Long userId = Long.parseLong(userIdStr);
        Long orgId = Long.parseLong(orgIdStr);
        Long tenantId = Long.parseLong(tenantIdStr);

        paramMap.put("userId", userId);
        paramMap.put("orgId", orgId);
        paramMap.put("tenantId", tenantId);

        //数据权限
        String roleIdStr = InvocationInfoProxy.getParameter(LoginContextConstant.RoleId);
        Long objId = RightObjectEnum.CUSTOMEROBJECT.getValue();
        Long actionId = (long) RightActionEnum.VIEW.getValue();
        String dataRightSql = rightService.getRightSql(Long.parseLong(roleIdStr), objId, actionId);
        paramMap.put("rightSql", dataRightSql);
        Page<CustomerDO> pageList = null;
        pageList = dao.pageSelect(CustomerDO.class, page, "selectByRight", "countByRight", paramMap);

        Page<CustomerVO> result = ModelUtil.copyPageModel(pageList, CustomerVO.class, new IConverter<CustomerDO, CustomerVO>() {
            @Override
            public void convert(CustomerDO origObj, CustomerVO destObj) {
                List<CustomerSalesVO> saleVos = ModelUtil.copyModelList(origObj.getSalesDOs(), CustomerSalesVO.class);
                destObj.setSalesVOs(saleService.transCustomerSale(saleVos));
            }
        });

        transCustomer(result.getData());

        return result;
    }

    public Page<CustomerVO> getMyRelList(Page<CustomerVO> page, Map<String, Object> paramMap) {
        return page;
    }

    public Page<CustomerVO> getMyFollowList(Page<CustomerVO> page, Map<String, Object> paramMap) {

        String userIdStr = (String) InvocationInfoProxy.getParameter("id");//用户id
        String orgIdStr = (String) InvocationInfoProxy.getParameter("orgid");//所属公司
        String tenantIdStr = (String) InvocationInfoProxy.getTenantid();
        Long userId = Long.parseLong(userIdStr);
        Long orgId = Long.parseLong(orgIdStr);
        Long tenantId = Long.parseLong(tenantIdStr);

        paramMap.put("userId", userId);
        paramMap.put("orgId", orgId);
        paramMap.put("tenantId", tenantId);

        Page<CustomerDO> pageList = dao.pageSelect(CustomerDO.class, page, "selectByFollow", "countByFollow", paramMap);
        Page<CustomerVO> result = ModelUtil.copyPageModel(pageList, CustomerVO.class, new IConverter<CustomerDO, CustomerVO>() {
            @Override
            public void convert(CustomerDO origObj, CustomerVO destObj) {
                List<CustomerSalesVO> saleVos = ModelUtil.copyModelList(origObj.getSalesDOs(), CustomerSalesVO.class);
                destObj.setSalesVOs(saleService.transCustomerSale(saleVos));
            }
        });

        transCustomer(result.getData());
        return result;
    }

    public Page<CustomerVO> getMyViewList(Page<CustomerVO> page, Map<String, Object> paramMap) {

        String userIdStr = (String) InvocationInfoProxy.getParameter("id");//用户id
        String orgIdStr = (String) InvocationInfoProxy.getParameter("orgid");//所属公司
        String tenantIdStr = (String) InvocationInfoProxy.getTenantid();
        Long userId = Long.parseLong(userIdStr);
        Long orgId = Long.parseLong(orgIdStr);
        Long tenantId = Long.parseLong(tenantIdStr);

        paramMap.put("userId", userId);
        paramMap.put("orgId", orgId);
        paramMap.put("tenantId", tenantId);

        Page<CustomerDO> pageList = dao.pageSelect(CustomerDO.class, page, "selectByView", "countByView", paramMap);
        Page<CustomerVO> result = ModelUtil.copyPageModel(pageList, CustomerVO.class, new IConverter<CustomerDO, CustomerVO>() {
            @Override
            public void convert(CustomerDO origObj, CustomerVO destObj) {
                List<CustomerSalesVO> saleVos = ModelUtil.copyModelList(origObj.getSalesDOs(), CustomerSalesVO.class);
                destObj.setSalesVOs(saleService.transCustomerSale(saleVos));
            }
        });

        transCustomer(result.getData());
        return result;
    }

    public Map<String, Object> getViewUserList(Long cumId, Map<String, Object> paramMap) {
        //判断是否有数据权限
        Long actionId = (long) RightActionEnum.VIEW.getValue();
        String crmMessage = hasRight(actionId, cumId);
        if (crmMessage != null) {
            throw new CrmBusinessException(crmMessage);
        }

        String orgIdStr = (String) InvocationInfoProxy.getParameter("orgid");//所属公司
        String tenantIdStr = (String) InvocationInfoProxy.getTenantid();
        Long orgId = Long.parseLong(orgIdStr);
        Long tenantId = Long.parseLong(tenantIdStr);

        paramMap.put("orgId", orgId);
        paramMap.put("tenantId", tenantId);
        paramMap.put("cumId", cumId);

        List<Map<String, Object>> list = dao.selectList(CustomerDO.class, "viewUsers", paramMap);
        Map<String, Object> rs = new HashMap<String, Object>();
        rs.put("users", list);
        return rs;
    }

    public Map<String, Object> getFollowUserList(Long cumId, Map<String, Object> paramMap) {
        //判断是否有数据权限
        Long actionId = (long) RightActionEnum.VIEW.getValue();
        String crmMessage = hasRight(actionId, cumId);
        if (crmMessage != null) {
            throw new CrmBusinessException(crmMessage);
        }

        String orgIdStr = (String) InvocationInfoProxy.getParameter("orgid");//所属公司
        String tenantIdStr = (String) InvocationInfoProxy.getTenantid();
        Long orgId = Long.parseLong(orgIdStr);
        Long tenantId = Long.parseLong(tenantIdStr);

        paramMap.put("orgId", orgId);
        paramMap.put("tenantId", tenantId);
        paramMap.put("cumId", cumId);

        List<Map<String, Object>> list = dao.selectList(CustomerDO.class, "followUsers", paramMap);
        Map<String, Object> rs = new HashMap<String, Object>();
        rs.put("users", list);
        return rs;
    }

    public int checkNameExist(CustomerVO vo) {
        Map<String, Object> param = new HashedMap<String, Object>();
        param.put("name", vo.getName());
        Long id = vo.getId();
        param.put("id", id);

        int count = dao.countAll(CustomerDO.class, "checkNameExist", param);
        if (count > 0) {
            return 1;
        }
        return 0;
    }

    public int delete(Long id) {
        CustomerDO customer = new CustomerDO();
        customer.setId(id);
        //判断客户是否停用
        String disableMsg = checkCustomerDisable(customer.getId());
        if(disableMsg != null){
        	throw new CrmBusinessException(disableMsg);
        }
        int num = super.deleteVO(customer);
        return num;
    }

    public int updateState(Long id, int enableState) {
        //判断是否有数据权限
        Long actionId = (long) RightActionEnum.EDIT.getValue();
        String crmMessage = hasRight(actionId, id);
        if (crmMessage != null) {
            throw new CrmBusinessException(crmMessage);
        }
        
        String userIdStr = (String) InvocationInfoProxy.getParameter("id");// 用户id
        Long userId = Long.parseLong(userIdStr);
        
        //插入动态
        updateStateDym(id, enableState);
        
        Date date = new Date();
        CustomerDO customer = new CustomerDO();
        customer.setId(id);
        customer.setEnableState(enableState);
        customer.setEnableTime(date);
        customer.setEnableUserId(userId);
        customer.setSysModifiedTime(date);
        customer.setSysModifiedUserId(userId);
        return dao.updateSql(CustomerDO.class, "updateState", customer);
    }
    
    /**
     * 停启用生成动态
     * @param id
     * @param enableState
     */
    public void updateStateDym(Long id, int enableState){
    	UserVO user = getCurrentUser();
		Long[] relUserArr = handleRelUserList(id);
		CustomerVO vo = getDetail(id);
        switch (enableState) {
        case 1:
        	DymCumEnable cumEnable = new DymCumEnable(dynamicService, user, vo, relUserArr);
        	cumEnable.execute();
        	break;
        case 2:
        	DymCumDisable cumDisable = new DymCumDisable(dynamicService, user, vo, relUserArr);
        	cumDisable.execute();
        	break;
        default:
        	break;
        }
    }
    
    public void batchUpdateState(String[] ids, Integer enableState) {
        //判断是否有数据权限
        Long actionId = (long) RightActionEnum.EDIT.getValue();
        Long[] idArr = hasBatchRight(actionId, ids);
        if (idArr == null || idArr.length == 0) {
            throw new CrmBusinessException("没有该条数据的权限");
        }
        
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("ids", idArr);
        List<CustomerDO> cdos = dao.selectVoList(CustomerDO.class, "idsGetCustomer", param);
        List<String> afterCheck = new ArrayList<String>();
        for(CustomerDO cd:cdos){
        	if(cd.getIsGroup()==1){
        		afterCheck.add(cd.getId().toString());
        	}
        }
        String[] stringTemp = afterCheck.toArray(new String[0]);
        if (stringTemp == null || stringTemp.length == 0) {
            throw new CrmBusinessException("集团客户无法停用");
        }
        
        //插入动态
        if(stringTemp != null && stringTemp.length != 0){
        	for(String cumIdStr : stringTemp){
        		Long cumId = Long.parseLong(cumIdStr);
        		updateStateDym(cumId, enableState);
        	}
        }
        
        String userIdStr = (String) InvocationInfoProxy.getParameter("id");// 用户id
        Long userId = Long.parseLong(userIdStr);
        Date date = new Date();
        Map<String, Object> enableParaMap = new HashMap<String, Object>();
        enableParaMap.put("ids", stringTemp);
        enableParaMap.put("enableState", enableState);
        enableParaMap.put("enableUserId", userId);
        enableParaMap.put("enableTime", date);
        enableParaMap.put("sysModifiedUserId", userId);
        enableParaMap.put("sysModifiedTime", date);
        dao.updateSql(CustomerDO.class, "batchUpdateEnableState", enableParaMap);
    }

    public CustomerVO insert(CustomerVO customer) {
        int exist = checkNameExist(customer);
        if (exist == 1) {
            throw new CrmBusinessException("客户名称已存在");
        }
        CustomerDO tranDO = ModelUtil.copyModel(customer, CustomerDO.class, new IConverter<CustomerVO, CustomerDO>() {
            @Override
            public void convert(CustomerVO origObj, CustomerDO destObj) {
                List<CustomerSalesDO> saleVos = ModelUtil.copyModelList(origObj.getSalesVOs(), CustomerSalesDO.class);
                destObj.setSalesDO(saleVos);
            }
        });
        
        if(tranDO.getVerifyId() != null && !"".equals(tranDO.getVerifyId())){
        	checkVerifyIdExist(customer);
        	tranDO.setIsIdentified(1);
        }
        CustomerDO custDo = super.saveVO(tranDO);
        CustomerVO vo = ModelUtil.copyModel(custDo, CustomerVO.class);
        transCustomer(Arrays.asList(vo));
        return vo;
    }

    @Override
    protected void beforeSaveVO(CustomerDO custDo) {
        //新增时进行客户审核，在保存时做审核校验，其他情况在审核接口中做校验
//		if ((vo.getId() == 0) && (vo.getVerifyId() != null) && (!vo.getVerifyId().equals(""))) {
//			checkVerifyIdExist(vo);
//		}
        super.beforeSaveVO(custDo);
        String userIdStr = (String) InvocationInfoProxy.getParameter("id");//用户id
        String orgIdStr = (String) InvocationInfoProxy.getParameter("orgid");//所属公司
        Long userId = Long.parseLong(userIdStr);
        Long orgId = Long.parseLong(orgIdStr);
        Date date = new Date();
        custDo.setOrgId(orgId);
        custDo.setCreatedTime(date);
        custDo.setCreatedUserId(userId);
        custDo.setType(1); //客户类型默认为：经销商
        custDo.setState(18); //客户状态默认为：潜在客户
        custDo.setEnableState(1); //启用状态默认为：启用
    }

    @Override
    protected void afterSaveVO(CustomerDO custDo) {
        super.afterSaveVO(custDo);
        saleSave(custDo); //保存销售信息
        
        //插入动态
        CustomerVO vo = ModelUtil.copyModel(custDo, CustomerVO.class);
        UserVO user = getCurrentUser();
        Long[] relUserArr = null;
		DymCustomerCreate cusCreate = new DymCustomerCreate(dynamicService,user,vo,relUserArr);
		cusCreate.execute();
		if(custDo.getLatitude() != null && !"".equals(custDo.getLatitude())
				&& custDo.getLongitude() != null && !"".equals(custDo.getLongitude())){
			DymCumLocationSave locationCreate = new DymCumLocationSave(dynamicService, user, vo,relUserArr);
			locationCreate.execute();
		}
    }

    protected void saleSave(CustomerDO custDo) {
        String userIdStr = (String) InvocationInfoProxy.getParameter("id");// 用户id
        String deptIdStr = (String) InvocationInfoProxy.getParameter("deptid");// 所属部门
        Long userId = Long.parseLong(userIdStr);
        Long deptId = Long.parseLong(deptIdStr);

        CustomerSalesDO saleDO;
        if (custDo.getSalesDOs() != null && custDo.getSalesDOs().get(0) != null) {
            saleDO = custDo.getSalesDOs().get(0);
        } else {
            saleDO = new CustomerSalesDO();
        }
        saleDO.setCumId(custDo.getId());
        saleDO.setOrgId(custDo.getOrgId());
        saleDO.setOwnerDeptId(deptId);
        saleDO.setOwnerUserId(userId);
        saleDO.setCreatedTime(custDo.getCreatedTime());
        saleDO.setCreatedUserId(userId);
        saleService.saveVO(saleDO);
    }

    public CustomerVO update(CustomerVO customer) {
        //判断是否有数据权限
        Long actionId = (long) RightActionEnum.EDIT.getValue();
        String crmMessage = hasRight(actionId, customer.getId());
        if (crmMessage != null) {
            throw new CrmBusinessException(crmMessage);
        }
        
        //判断客户是否停用
        String disableMsg = checkCustomerDisable(customer.getId());
        if(disableMsg != null){
        	throw new CrmBusinessException(disableMsg);
        }
        
        if (customer.getName() != null && !(customer.getName().isEmpty())) {
            int exist = checkNameExist(customer);
            if (exist == 1) {
                throw new CrmBusinessException("客户名称已存在");
            }
        }
        //客户认证
        if(customer.getVerifyId() != null && !"".equals(customer.getVerifyId())){
        	checkVerifyIdExist(customer);
        	customer.setIsIdentified(1);
        }
        CustomerVO oriVo = getDetail(customer.getId());
        CustomerDO custDo = super.updateVO(ModelUtil.copyModel(customer, CustomerDO.class));
        CustomerVO vo = ModelUtil.copyModel(custDo, CustomerVO.class, new IConverter<CustomerDO, CustomerVO>() {
            @Override
            public void convert(CustomerDO origObj, CustomerVO destObj) {
                List<CustomerSalesVO> saleVos = ModelUtil.copyModelList(origObj.getSalesDOs(), CustomerSalesVO.class);
                destObj.setSalesVOs(saleService.transCustomerSale(saleVos));
            }
        });
        //插入动态
        if(!oriVo.getName().equals(customer.getName())){//客户名称修改
    		UserVO user = getCurrentUser();
    		Long[] relUserArr = handleRelUserList(customer.getId());
    		DymCustomerUpdate cusUpdate = new DymCustomerUpdate(dynamicService, user, oriVo, vo,relUserArr);
    		cusUpdate.execute();
        }
        if((oriVo.getLatitude() != null && !oriVo.getLatitude().equals(customer.getLatitude()))
        		|| (oriVo.getLongitude() != null && !oriVo.getLongitude().equals(customer.getLongitude()))){//客户位置变更
        	UserVO user = getCurrentUser();
    		Long[] relUserArr = handleRelUserList(customer.getId());
        	DymCumLocationUpdate locationUpdate = new DymCumLocationUpdate(dynamicService, user, vo, relUserArr);
        	locationUpdate.execute();
        }
        
        transCustomer(Arrays.asList(vo));
        return vo;
    }
    
    public CustomerVO updateNoAuthority(CustomerVO customer) {

        if (customer.getName() != null && !(customer.getName().isEmpty())) {
            int exist = checkNameExist(customer);
            if (exist == 1) {
                throw new CrmBusinessException("客户名称已存在");
            }
        }
        
        CustomerDO custDo = super.updateVO(ModelUtil.copyModel(customer, CustomerDO.class));
        CustomerVO vo = ModelUtil.copyModel(custDo, CustomerVO.class);
        
        return vo;
    }

    @Override
    protected void beforeUpdateVO(CustomerDO custDo) {

        super.beforeUpdateVO(custDo);
        String userIdStr = (String) InvocationInfoProxy.getParameter("id");//用户id
        Long userId = Long.parseLong(userIdStr);
        Date date = new Date();
        custDo.setModifiedTime(date);
        custDo.setModifiedUserId(userId);
        custDo.setType(1); //客户类型默认为：经销商
        custDo.setState(18); //客户状态默认为：潜在客户
    }

    @Override
    protected void afterUpdateVO(CustomerDO custDo) {
        super.afterUpdateVO(custDo);
    }

    @Override
    protected void beforeDeleteVO(CustomerDO custDo) {
    	if(custDo.getIsGroup()==2){
    		throw new CrmBusinessException("集团客户不能删除");
    	}
    	//判断是否有数据权限
        Long actionId = (long) RightActionEnum.DELETE.getValue();
        String crmMessage = hasRight(actionId, custDo.getId());
        if (crmMessage != null) {
            throw new CrmBusinessException(crmMessage);
        }
        String userIdStr = (String) InvocationInfoProxy.getParameter("id");// 用户id
        Long userId = Long.parseLong(userIdStr);
        Date date = new Date();
        custDo.setDeletedTime(date);
        custDo.setDeletedUserId(userId);
        custDo.setSysModifiedTime(date);
        custDo.setSysModifiedUserId(userId);
    }

    @Override
    protected void afterDeleteVO(CustomerDO custDo) {
        saleService.delete(custDo.getId());
    }

    public int batchDelete(String[] ids) {
        //判断是否有数据权限
        Long actionId = (long) RightActionEnum.DELETE.getValue();
        Long[] idArr = hasBatchRight(actionId, ids);
        if (idArr == null || idArr.length == 0) {
            throw new CrmBusinessException("没有该条数据的权限");
        }
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("ids", idArr);
        List<CustomerDO> cdos = dao.selectVoList(CustomerDO.class, "idsGetCustomer", param);
        List<String> afterCheck = new ArrayList<String>();
        for(CustomerDO cd:cdos){
        	//判断客户是否停用
            String disableMsg = checkCustomerDisable(cd.getId());
            if(disableMsg != null){
            	continue;
            }
        	
        	if(cd.getIsGroup()==1){
        		afterCheck.add(cd.getId().toString());
        	}
        }
        String[] stringTemp = afterCheck.toArray(new String[0]);
        if (stringTemp == null || stringTemp.length == 0) {
            throw new CrmBusinessException("该客户不能删除");
        }
        int delNum = super.batchDeleteByIDs(CustomerDO.class, stringTemp);
        saleService.batchDeleteByCumIds(stringTemp);
        viewService.batchDeleteByCumIds(stringTemp);
        return delNum;
    }

    public Object selectFieldsByIds(Object[] ids) {
        Map<String, Object> para = new HashMap<String, Object>();
        para.put("ids", ids);
        return dao.selectList(CustomerDO.class, "selectFieldsByIds", para);
    }

    private List<CustomerVO> transCustomer(List<CustomerVO> customerList) {
        List<FieldRelation<CustomerVO>> relations = new ArrayList<FieldRelation<CustomerVO>>();
        //业务类型
        relations.add(new RefFieldRelation<CustomerVO>(CustomerVO.class, "biztypeId", new String[]{"biztypeName"}, biztypeService, "selectFieldsByIds"));
        //基础档案：1-客户类型、2-渠道类型、5-客户等级、6-客户状态
        relations.add(new RefFieldRelation<CustomerVO>(CustomerVO.class, "type", new String[]{"typeName"}, baseDocDetailBizService, "selectFieldsByIds"));
        relations.add(new RefFieldRelation<CustomerVO>(CustomerVO.class, "cannelType", new String[]{"cannelTypeName"}, baseDocDetailBizService, "selectFieldsByIds"));
        relations.add(new RefFieldRelation<CustomerVO>(CustomerVO.class, "level", new String[]{"levelName"}, baseDocDetailBizService, "selectFieldsByIds"));
        relations.add(new RefFieldRelation<CustomerVO>(CustomerVO.class, "state", new String[]{"stateName"}, baseDocDetailBizService, "selectFieldsByIds"));
        //行业
        relations.add(new RefFieldRelation<CustomerVO>(CustomerVO.class, "industry", new String[]{"industryName"}, IndustryBizService, "selectFieldsByIds"));
        //上级客户
        relations.add(new RefFieldRelation<CustomerVO>(CustomerVO.class, "parentId", new String[]{"parentName"}, this, "selectFieldsByIds"));
        //省、市、区
        relations.add(new RefFieldRelation<CustomerVO>(CustomerVO.class, "province", new String[]{"provinceName"}, regionService, "selectFieldsByIds"));
        relations.add(new RefFieldRelation<CustomerVO>(CustomerVO.class, "city", new String[]{"cityName"}, regionService, "selectFieldsByIds"));
        relations.add(new RefFieldRelation<CustomerVO>(CustomerVO.class, "district", new String[]{"districtName"}, regionService, "selectFieldsByIds"));
        //启用标识
        relations.add(new EnumFieldRelation<CustomerVO>(CustomerVO.class, "enableState", "enableStateName", enumService, "enable_state"));
        //集团客户标识
        relations.add(new EnumFieldRelation<CustomerVO>(CustomerVO.class, "isGroup", "isGroupName", enumService, "cum_sign"));
        new FieldRelationHandler<CustomerVO>().handler(customerList, relations);
        return customerList;
    }

    public List<ReferDataVO> getRefervalues(Page<CustomerVO> page, Map<String, Object> paraMap) {
        // TODO 加权限
        Page<CustomerDO> pageDO = dao.pageSelect(CustomerDO.class, page, "selectRefervalues", "countRefervalues", paraMap);
        List<CustomerDO> doList = pageDO.getData();

        List<ReferDataVO> rsList = new ArrayList<ReferDataVO>();
        for (CustomerDO custDo : doList) {
            ReferDataVO referDataVO = new ReferDataVO();
            referDataVO.setId(custDo.getId().toString());
            referDataVO.setValue(custDo.getName());

            rsList.add(referDataVO);
        }
        return rsList;
    }

    public List<CustomerVO> getRefervaluesForApp(Page<CustomerVO> page, Map<String, Object> paraMap) {
        // TODO 加权限
        Page<CustomerDO> pageDO = dao.pageSelect(CustomerDO.class, page, "selectRefervalues", "countRefervalues", paraMap);
        Page<CustomerVO> result = ModelUtil.copyPageModel(pageDO, CustomerVO.class);
        List<CustomerVO> voList = result.getData();
        return voList;
    }

    //参照列表
    public List<CustomerVO> getRefList(Map<String, Object> paraMap) {
        if (paraMap == null) {
            paraMap = new HashMap<String, Object>();
        }
        paraMap.put("tenantId", new Long(InvocationInfoProxy.getTenantid()));
        List<CustomerVO> result = ModelUtil.copyModelList(dao.selectVoList(CustomerDO.class, "getRefList", paraMap), CustomerVO.class);
        return result;
    }

    //分页参照列表
    public Page<CustomerVO> getRefPage(Page<CustomerVO> page, Map<String, Object> paraMap) {
        if (paraMap == null) {
            paraMap = new HashMap<String, Object>();
        }

        //数据权限
        String roleIdStr = InvocationInfoProxy.getParameter(LoginContextConstant.RoleId);
        Long objId = RightObjectEnum.CUSTOMEROBJECT.getValue();
        Long actionId = (long) RightActionEnum.VIEW.getValue();
        String dataRightSql = rightService.getRightSql(Long.parseLong(roleIdStr), objId, actionId);
        paraMap.put("rightSql", dataRightSql);
        paraMap.put("tenantId", new Long(InvocationInfoProxy.getTenantid()));
        Page<CustomerDO> pageList = dao.pageSelect(CustomerDO.class, page, "getRefPage", "countRefPage", paraMap);
        Page<CustomerVO> result = ModelUtil.copyPageModel(pageList, CustomerVO.class);
        transCustomer(result.getData());
        return result;
    }

    /**
     * 判断公司是否已被核实
     * @param paraMap
     * @return
     */
    public boolean getIdentifyFlag(Map<String, Object> paraMap) {
        boolean flag = false;
        CustomerDO customer = (CustomerDO) dao.selectOne(CustomerDO.class, "selectVOByVerifyId", paraMap);
        if (customer != null) {
            throw new CrmBusinessException("该公司已被" + customer.getName() + "客户认证");
        }
        return flag;
    }
    
    /**
     * 根据verifyId判断是否已被核实
     * @param vo
     */
    public void checkVerifyIdExist(CustomerVO vo) {
        Map<String, Object> param = new HashedMap<String, Object>();
        param.put("verifyId", vo.getVerifyId());
        Long id = vo.getId();
        param.put("id", id);
        CustomerDO customer = (CustomerDO) dao.selectOne(CustomerDO.class, "selectVOByVerifyId", param);
        if (customer != null) {
            throw new CrmBusinessException("该公司已被" + customer.getName() + "客户认证");
        }
    }
    
    /**
     * 根据verifyFullname判断是否已被核实
     * @param id
     * @param verifyName
     * @return
     */
    public boolean checkVerifyNameExist(String id, String verifyName) {
        Map<String, Object> param = new HashedMap<String, Object>();
        param.put("verifyFullname", verifyName);
        param.put("id", id);
        CustomerDO customer = (CustomerDO) dao.selectOne(CustomerDO.class, "selectVOByVerifyName", param);
        if (customer != null) {
            return true;
        }
        return false;
    }
    
    /**
     * 企业核实
     * @param vo
     * @return
     */
    public CustomerVO identify(CustomerVO vo) {
        checkVerifyIdExist(vo);
        CustomerDO custDO = ModelUtil.copyModel(vo, CustomerDO.class);
        dao.update(custDO);
        vo = ModelUtil.copyModel(custDO, CustomerVO.class);
		// 插入动态(公司客户认证)
		UserVO user = getCurrentUser();
		Long[] relUserArr = handleRelUserList(vo.getId());
		DymCumIdentify cumIdentify = new DymCumIdentify(dynamicService, user,vo, relUserArr);
		cumIdentify.execute();
		// 插入动态(集团客户认证)
		DymGCumIdentify gCumIdentify = new DymGCumIdentify(dynamicService,user, vo, relUserArr);
		gCumIdentify.execute();
        transCustomer(Arrays.asList(vo));
        return vo;
    }
    
    /**
     * 取消核实
     * @param vo
     * @return
     */
    public CustomerVO cancelIdentify(CustomerVO vo) {
        CustomerDO custDO = ModelUtil.copyModel(vo, CustomerDO.class);
        dao.update(custDO);
        vo = ModelUtil.copyModel(custDO, CustomerVO.class);
        //插入动态(公司客户)
        UserVO user = getCurrentUser();
		Long[] relUserArr = handleRelUserList(vo.getId());
        DymCumIdentifyCancel cumIdentifyCan = new DymCumIdentifyCancel(dynamicService, user, vo,relUserArr);
        cumIdentifyCan.execute();
        //插入动态(集团客户)
        DymGCumIdentifyCancel gCumIdentifyCan = new DymGCumIdentifyCancel(dynamicService, user, vo,relUserArr);
        gCumIdentifyCan.execute();
        
        transCustomer(Arrays.asList(vo));
        return vo;
    }

    /**
     * 变更负责人（或分配负责人）
     *
     * @param paraMap
     */
    public void changeOwner(Map<String, Object> paraMap) {
        CustomerSalesDO customerSale = new CustomerSalesDO();
        customerSale.setCumId(Long.valueOf(String.valueOf(paraMap.get("cumId"))));
        customerSale.setTenantId(Long.valueOf(InvocationInfoProxy.getTenantid()));
        String preOwnerUserIdStr = String.valueOf(paraMap.get("preOwnerUserId"));
        String newOwnerUserIdStr = String.valueOf(paraMap.get("newOwnerUserId"));
        JSONArray relatechangeowner = (JSONArray)paraMap.get("relatechangeowner");
        if ((newOwnerUserIdStr != null) && (!newOwnerUserIdStr.equals("")) && (!newOwnerUserIdStr.equals("0"))) {
            Long newOwnerUserId = Long.valueOf(newOwnerUserIdStr);
            Map<String, Object> userLoginInfo = userService.getLoginContext(newOwnerUserId);
            customerSale.setOwnerUserId(newOwnerUserId);
            customerSale.setOwnerDeptId(Long.valueOf(String.valueOf(userLoginInfo.get("deptId"))));
             customerSale.setOrgId(Long.valueOf(String.valueOf(userLoginInfo.get("orgId"))));

            for (Object relatetype : relatechangeowner.toArray()) {
                if("opportunity".equals(relatetype)) {
                    //如果有商机，我们变更负责人 也要变更客户下 所有商机的 负责人
                    OpportunityVO oppVO = new OpportunityVO();
                    oppVO.setCustomerId(Long.valueOf(String.valueOf(paraMap.get("cumId"))));
                    oppVO.setOwnerUserId(Long.valueOf(newOwnerUserId));
                    oppVO.setDeptId(Long.valueOf(String.valueOf(userLoginInfo.get("deptId"))));
                    oppVO.setOrgId(Long.valueOf(String.valueOf(userLoginInfo.get("orgId"))));
                    oppVO.setTenantId(Long.valueOf(InvocationInfoProxy.getTenantid()));
                    oppVO.setSysModifiedTime(new Date());
                    oppVO.setSysModifiedUserId(Long.valueOf(InvocationInfoProxy.getParameter(LoginContextConstant.UserId)));
                    oppService.changeOwner(oppVO);
                } else if ("contact".equals(relatetype)) {
                    //如果有联系人， 我们变更客户下 所有联系人的负责人
                    ContactDO contactDO = new ContactDO();
                    contactDO.setCustomer(Long.valueOf(String.valueOf(paraMap.get("cumId"))));
                    contactDO.setOwnerUserId(Long.valueOf(newOwnerUserId));
                    contactDO.setDeptId(Long.valueOf(String.valueOf(userLoginInfo.get("deptId"))));
                    contactDO.setOrgId(Long.valueOf(String.valueOf(userLoginInfo.get("orgId"))));
                    contactDO.setTenantId(Long.valueOf(InvocationInfoProxy.getTenantid()));
                    contactDO.setSysModifiedTime(new Date());
                    contactDO.setSysModifiedUserId(Long.valueOf(InvocationInfoProxy.getParameter(LoginContextConstant.UserId)));
                    contactService.changeOwner(contactDO);
                }
            }
        }

        if ((preOwnerUserIdStr != null) && (!preOwnerUserIdStr.equals("")) && (!preOwnerUserIdStr.equals("0"))) {
            Map<String, Object> param = new HashMap<>();
            param.put("cumId", paraMap.get("cumId"));
            param.put("tenantId", InvocationInfoProxy.getTenantid());
            param.put("orgId", InvocationInfoProxy.getParameter(LoginContextConstant.OrgId));
            List<CustomerSalesVO> list = saleService.selectByCustomer(param);
            if (list != null && list.size() > 0) {
            	//插入动态
            	UserVO user = getCurrentUser();
            	UserVO oriUser = userService.getDetail(Long.parseLong(preOwnerUserIdStr));
            	UserVO destUser = userService.getDetail(customerSale.getOwnerUserId());
            	Long[] relUserArr = handleRelUserList(customerSale.getCumId());
            	CustomerVO vo = getDetail(customerSale.getCumId());
            	DymCumStaffUpdate staffUpdate = new DymCumStaffUpdate(dynamicService, user, vo, oriUser, destUser,relUserArr);
            	staffUpdate.execute();
            	
                customerSale.setId(list.get(0).getId());
                saleService.update(ModelUtil.copyModel(customerSale, CustomerSalesVO.class));
            } else {
            	//插入动态
            	UserVO user = getCurrentUser();
            	Long[] relUserArr = handleRelUserList(customerSale.getCumId());
            	CustomerVO vo = getDetail(customerSale.getCumId());
            	UserVO destUser = userService.getDetail(customerSale.getOwnerUserId());
            	DymCumStaffAdd staffAdd = new DymCumStaffAdd(dynamicService, user, vo, destUser,relUserArr);
            	staffAdd.execute();
            	
                saleService.insert(ModelUtil.copyModel(customerSale, CustomerSalesVO.class));
            }
        } else {
        	//插入动态
        	UserVO user = getCurrentUser();
        	Long[] relUserArr = handleRelUserList(customerSale.getCumId());
        	CustomerVO vo = getDetail(customerSale.getCumId());
        	UserVO destUser = userService.getDetail(customerSale.getOwnerUserId());
        	DymCumStaffAdd staffAdd = new DymCumStaffAdd(dynamicService, user, vo, destUser,relUserArr);
        	staffAdd.execute();
        	
            saleService.insert(ModelUtil.copyModel(customerSale, CustomerSalesVO.class));
        }
    }


    private String hasRight(Long actionId, Long id) {
        // 判断是否有数据权限
        String roleIdStr = InvocationInfoProxy.getParameter(LoginContextConstant.RoleId);
        Long objId = RightObjectEnum.CUSTOMEROBJECT.getValue();
        boolean haRight = rightService.hasRight(Long.parseLong(roleIdStr), objId, actionId, id);
        if (!haRight) {
            return "没有该条数据的权限";
        }
        return null;
    }

    private Long[] hasBatchRight(Long actionId, String[] ids) {
        String roleIdStr = InvocationInfoProxy.getParameter(LoginContextConstant.RoleId);
        Long objId = RightObjectEnum.CUSTOMEROBJECT.getValue();
        Long[] LongTemp = new Long[ids.length];
        for (int i = 0; i < ids.length; i++) {
            LongTemp[i] = Long.parseLong(ids[i]);
        }
        Long[] idArr = rightService.filterWithRight(Long.parseLong(roleIdStr), objId, actionId, LongTemp);
        return idArr;
    }

    public List<Map<String, Object>> getCustomerRelatedlist(String customerId, String type) {
        List<Map<String, Object>> detailList = new ArrayList<>();
        long cusId = Long.parseLong(customerId);
        //如果type类型是空的  我们要返回客户所有相关对象的数据 注意：这时候每个相关对象 最多只显示 3条
        if(StringUtils.isEmpty(type)) {
            Map<String, Object> oppForCusMap = oppService.getOppForCusRelate(cusId, 3);
            Map<String, Object> cumprmForCusMap = cumprmService.getRelListForApp(cusId, 3);
            Map<String, Object> cusreluserForCusMap = cusreluserService.getRelUserForcusRel(cusId, null);
            Map<String, Object> contactForCusMap = contactService.getRelatedListForApp(cusId, 3);
            if(oppForCusMap.size() > 0) {
                detailList.add(oppForCusMap);
            }
            if(cumprmForCusMap.size() > 0) {
                detailList.add(cumprmForCusMap);
            }
                detailList.add(cusreluserForCusMap);
                detailList.add(contactForCusMap);
        } else if("opportunity" .equals(type)) {//当 type 字段 有值时，这时候证明app在调用获取该type字段的所有相关数据
            Map<String, Object> oppForCusMap = oppService.getOppForCusRelate(cusId, null);
            if(oppForCusMap.size() > 0) {
                detailList.add(oppForCusMap);
            }
        } else if("cumprmt". equals(type)) {
            Map<String, Object> cumprmForCusMap = cumprmService.getRelListForApp(cusId, null);
            if(cumprmForCusMap.size() > 0) {
                detailList.add(cumprmForCusMap);
            }
        } else if("contact". equals(type)) {
            Map<String, Object> contactForCusMap = contactService.getRelatedListForApp(cusId, null);
            if(contactForCusMap.size() > 0) {
                detailList.add(contactForCusMap);
            }
        } else if("customerReluser". equals(type)) {
            Map<String, Object> cusreluserForCusMap = cusreluserService.getRelUserForcusRel(cusId, null);
            if(cusreluserForCusMap.size() > 0) {
                detailList.add(cusreluserForCusMap);
            }
        }

        return detailList;
    }

    /**
     * 根据部门id 或 负责人id  获取客户地图信息
     *
     * @param deptid
     * @param personIDs
     * @return
     */
    public List<Map<String, Object>> getCustomerMap(String deptid, List<String> personIDs) {
        Map<String, Object> param = new HashMap<>();
        String tenantIdStr = (String) InvocationInfoProxy.getTenantid();
        param.put("tenantId", tenantIdStr);
        param.put("sorgId", InvocationInfoProxy.getParameter(LoginContextConstant.OrgId));
        if (personIDs.size() > 0) {
            //如果负责人id有值 首先按照负责人查询客户地图信息
            param.put("ownerIds", personIDs.toArray(new String[0]));
        } else if (StringUtils.isNotEmpty(deptid)) {
            //如果负责人id没传过来 ， 那么我们按照部门id 获取客户地图信息
            param.put("deptid", deptid);
        }
        //数据权限
        String roleIdStr = InvocationInfoProxy.getParameter(LoginContextConstant.RoleId);
        Long objId = RightObjectEnum.CUSTOMEROBJECT.getValue();
        Long actionId = (long) RightActionEnum.VIEW.getValue();
        String dataRightSql = rightService.getRightSql(Long.parseLong(roleIdStr), objId, actionId);
        param.put("rightSql", dataRightSql);
        
        List<CustomerDO> cusVOs = dao.selectVoList(CustomerDO.class, "getCustomerMapInfo", param);
        List<CustomerVO> customerVOList = ModelUtil.copyModelList(cusVOs, CustomerVO.class, new IConverter<CustomerDO, CustomerVO>() {
            @Override
            public void convert(CustomerDO origObj, CustomerVO destObj) {
                List<CustomerSalesVO> saleVos = ModelUtil.copyModelList(origObj.getSalesDOs(), CustomerSalesVO.class);
                destObj.setSalesVOs(saleService.transCustomerSale(saleVos));
            }
        });
        List<CustomerVO> customerVOS = transCustomer(customerVOList);

        List<Map<String, Object>> cusmaplist = new ArrayList<>();
        if (customerVOS != null) {

            for (CustomerVO cusVO : customerVOS) {
                Map<String, Object> cusInfoMap = new HashMap<>();
                cusInfoMap.put("cusid", cusVO.getId());
                cusInfoMap.put("cusname", cusVO.getName());
                List<String> telList = new ArrayList<>();
                if(StringUtils.isNotEmpty(cusVO.getTel())) {
                    telList.add(cusVO.getTel());
                }
                if(StringUtils.isNotEmpty(cusVO.getMobile())) {
                    telList.add(cusVO.getMobile());
                }
                cusInfoMap.put("tel", telList);
                cusInfoMap.put("owner", cusVO.getSalesVOs().get(0).getOwnerUserName());
                Map<String, Object> location = new HashMap<>();
//                location.put("address", cusVO.getAddress());
                location.put("address", cusVO.getStreet());
                location.put("longitude", cusVO.getLongitude());
                location.put("latitude", cusVO.getLatitude());
                location.put("altitude", cusVO.getAltitude());
                cusInfoMap.put("location", location);
                cusmaplist.add(cusInfoMap);
            }
        }
        return cusmaplist;
    }

    public void delrelate(String id, String relateid, String type) {
        if("customerReluser".equals(type)) {
            Long cusreluserId = Long.parseLong(relateid);
            cusreluserService.delete(cusreluserId);
        } else {
            throw new CrmBusinessException("暂不支持该相关对象移除");
        }
    }
    
    public DynamicVO[] getCumDynamic(Long cumId) {
		Long curUser = Long.parseLong(InvocationInfoProxy.getParameter(LoginContextConstant.UserId));
		DynamicVO[] dyms = dynamicService.getBusiDynamic(MtObjTypeEnum.CUSTOMER.getValue(), cumId);
		CustomerVO customer = getDetail(cumId);
		Field bFromField = new Field("",new Link("","CUSTOMER",cumId,"",""));
		Field bToField = new Field("该",new Link("客户","CUSTOMER",cumId,"",""));
		BusiFilter busiFilter = new BusiFilter(bFromField,bToField);
		MyFilter myFilter = new MyFilter(curUser,"我");
		DateTimeFilter dtFilter = new DateTimeFilter(System.currentTimeMillis());
		for(int i=0,len=dyms.length;i<len;i++) {
			busiFilter.doFilter(dyms[i]);
			myFilter.doFilter(dyms[i]);
			dtFilter.doFilter(dyms[i]);
		}
		return dyms;
	}
    
    /**
	 * 获取当前登录用户
	 * @return
	 */
	public UserVO getCurrentUser(){
		Long curUser = Long.parseLong(InvocationInfoProxy.getParameter(LoginContextConstant.UserId));
		UserVO user = userService.getDetail(curUser);
		return user;
	}
	
	public Long[] handleRelUserList(Long cumId){
		String orgIdStr = InvocationInfoProxy.getParameter(LoginContextConstant.OrgId);
		Long orgId = Long.parseLong(orgIdStr);
		Long[] idArr = new Long[]{};
		List<Long> idList = new ArrayList<Long>();
		//查询公司客户负责人，添加到dynamic_follow表中
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("cumId", cumId);
		param.put("tenantId", InvocationInfoProxy.getTenantid());
		List<CustomerSalesVO> salesList = saleService.selectByCustomer(param);
		if(salesList != null && salesList.size() > 0){
			for(CustomerSalesVO cumSale : salesList){
				if(cumSale.getOrgId().equals(orgId)){
					idList.add(cumSale.getOwnerUserId());
				}
			}
		}
		//查询客户参与人，添加到dynamic_follow表中
		List<CustomerRelusersVO> refuserList = cusreluserService.getCumRelusers(cumId);
		if(refuserList != null && refuserList.size() > 0){
			for(CustomerRelusersVO relUser : refuserList){
				idList.add(relUser.getUserId());
			}
			if(idList != null && idList.size() > 0){
				idArr = idList.toArray(new Long[0]);
			}
		}
		return idArr;
	}
	
	public Map<String, List<String>> getCustomerFuncList(Map<String, Object> param){
		List<FuncresourceVO> fcList = funcService.getFuncResourceList(param);
		Map<String, List<String>> action = new HashMap<String, List<String>>();
		List<String> actionList = new ArrayList<String>();
		if(fcList != null && fcList.size() > 0){
			for(FuncresourceVO fc : fcList){
				if(fc.getResRemark()!=null && !"".equals(fc.getResRemark())){
					String resRemark = fc.getResRemark();
					switch (resRemark) {
					case "customer:list:add:customer":
						actionList.add("add");
						break;
					case "customer:view:edit:customer":
						actionList.add("edit");
						break;
					case "customer:view:upgrade:customer":
						actionList.add("upgrade");
						break;
					default:
						break;
					}
				}
			}
			action.put("actions", actionList);
		}
		return action;
	}

    public void addrelate(String id, List<String> relateArry) {
        if(relateArry != null && relateArry.size() > 0) {
            for(String relate : relateArry) {
                CustomerRelusersVO cusRelVO = new CustomerRelusersVO();
                cusRelVO.setCumId(Long.parseLong(id));
                cusRelVO.setUserId(Long.parseLong(relate));
                cusreluserService.insert(cusRelVO);
            }
        }

    }
    
	private String checkCustomerDisable(Long cumId) {
		CustomerVO customer = getDetail(cumId);
		if(customer.getEnableState() == 2){
			return "该客户已停用";
		}
		return null;
	}
}
